import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, message, Row, Col, Tabs, Tag } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import type { ColumnsType } from 'antd/es/table';
import styles from './index.module.css';
import { textApi } from '../../../services/api/text';

const { TabPane } = Tabs;

interface HistoryRecord {
    algorithmConfigName: string;
    algorithmId: number;
    algorithmName: string;
    createdAt: string;
    resultId: number;
    score: number;
    textId1: number;
    textId2: number;
}

interface PageParams {
    pageNo: number;
    pageSize: number;
}

const SimilarityAnalysisHistory: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<HistoryRecord[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const [currentResult, setCurrentResult] = useState<any>(null);
    const [detailLoading, setDetailLoading] = useState(false);

    const columns: ColumnsType<HistoryRecord> = [
        {
            title: '分析ID',
            dataIndex: 'resultId',
            key: 'resultId',
            width: 100,
        },
        {
            title: '算法名称',
            dataIndex: 'algorithmName',
            key: 'algorithmName',
            width: 150,
            render: (text: string, record: HistoryRecord) => (
                <Tag color="blue">{text}</Tag>
            ),
        },
        {
            title: '算法配置',
            dataIndex: 'algorithmConfigName',
            key: 'algorithmConfigName',
            width: 150,
        },
        {
            title: '文本ID',
            key: 'textIds',
            width: 200,
            render: (_, record) => (
                <Space>
                    <Tag color="green">Text1: {record.textId1}</Tag>
                    <Tag color="orange">Text2: {record.textId2}</Tag>
                </Space>
            ),
        },
        {
            title: '相似度得分',
            dataIndex: 'score',
            key: 'score',
            width: 120,
            render: (score: number) => (
                <Tag color={getScoreColor(score)}>
                    {(score * 100).toFixed(2)}%
                </Tag>
            ),
            sorter: (a, b) => a.score - b.score,
        },
        {
            title: '分析时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
            sorter: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record) => (
                <Button
                    type="primary"
                    icon={<EyeOutlined />}
                    onClick={() => handleViewDetail(record.resultId)}
                >
                    查看详情
                </Button>
            ),
        },
    ];

    const fetchAnalysisHistory = async (params: PageParams) => {
        try {
            setLoading(true);
            const response = await textApi.pageAnalysis(params);
            if (response.code === 200) {
                setData(response.data.result);
                setPagination({
                    current: params.pageNo,
                    pageSize: params.pageSize,
                    total: response.data.total
                });
            } else {
                message.error(response.message || '获取分析历史失败');
            }
        } catch (error) {
            message.error('获取分析历史失败');
        } finally {
            setLoading(false);
        }
    };

    const handleViewDetail = async (resultId: number) => {
        try {
            setDetailLoading(true);
            const response = await textApi.getResultById(resultId);
            if (response.code === 200) {
                setCurrentResult(response.data);
                setDetailModalVisible(true);
            } else {
                message.error(response.message || '获取分析详情失败');
            }
        } catch (error) {
            message.error('获取分析详情失败');
        } finally {
            setDetailLoading(false);
        }
    };

    const handleTableChange = (pagination: any, filters: any, sorter: any) => {
        fetchAnalysisHistory({
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        });
    };

    const getScoreColor = (score: number) => {
        if (score >= 0.7) return 'success';
        if (score >= 0.4) return 'warning';
        return 'error';
    };

    useEffect(() => {
        fetchAnalysisHistory({
            pageNo: 1,
            pageSize: 10
        });
    }, []);

// 仪表盘配置
    const getEnhancedGaugeOption = () => {
        if (!currentResult || !currentResult.chartData || !currentResult.chartData.similarityGauge) {
            return {
                series: [{
                    type: 'gauge',
                    startAngle: 180,
                    endAngle: 0,
                    min: 0,
                    max: 1,
                    splitNumber: 10,
                    data: [{ value: 0, name: '相似度得分' }]
                }]
            };
        }

        // 定义默认的阈值
        const defaultThresholds = {
            high: 0.7,
            medium: 0.4,
            low: 0.3
        };

        const { score } = currentResult.chartData.similarityGauge;
        const thresholds = currentResult.chartData.similarityGauge.thresholds || defaultThresholds;
        return {
            series: [{
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 1,
                splitNumber: 10,
                itemStyle: {
                    color: score >= thresholds.high ? '#67e0e3' :
                        score >= thresholds.medium ? '#37a2da' :
                            score >= thresholds.low ? '#fd666d' : '#ff0000'
                },
                progress: {
                    show: true,
                    width: 30,
                    roundCap: true,
                    clip: false
                },
                pointer: {
                    show: true,
                    width: 6
                },
                axisLine: {
                    lineStyle: {
                        width: 30,
                        color: [
                            [thresholds.low, '#fd666d'],
                            [thresholds.medium, '#37a2da'],
                            [thresholds.high, '#67e0e3'],
                            [1, '#37a2da']
                        ]
                    }
                },
                axisTick: {
                    distance: -45,
                    splitNumber: 5,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -52,
                    length: 14,
                    lineStyle: {
                        width: 3,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -20,
                    color: '#999',
                    fontSize: 12,
                    formatter: function(value: number) {
                        if (value === 1) return '高';
                        if (value === 0) return '低';
                        return value.toString();
                    }
                },
                title: {
                    offsetCenter: [0, '20%'],
                    fontSize: 14
                },
                detail: {
                    valueAnimation: true,
                    width: '60%',
                    lineHeight: 40,
                    borderRadius: 8,
                    offsetCenter: [0, '60%'],
                    fontSize: 40,
                    fontWeight: 'bolder',
                    formatter: function(value: number) {
                        return value.toFixed(2);
                    },
                    color: 'inherit'
                },
                data: [{
                    value: score,
                    name: '相似度得分'
                }]
            }]
        };
    };

// 雷达图配置
    const getRadarOption = () => {
        if (!currentResult || !currentResult.analysisDetails) {
            return {
                title: { text: '暂无数据' }
            };
        }

        const details = currentResult.analysisDetails;
        return {
            title: {
                text: '文本特征对比'
            },
            legend: {
                data: ['文本1', '文本2']
            },
            radar: {
                indicator: [
                    { name: '文本长度', max: Math.max(details.text1Length, details.text2Length) },
                    { name: '唯一词数', max: Math.max(details.uniqueText1Count, details.uniqueText2Count) },
                    { name: '共同词数', max: details.commonTermsCount },
                    { name: '相似度', max: 1 },
                    { name: '词汇丰富度', max: 1 }
                ]
            },
            series: [{
                type: 'radar',
                data: [
                    {
                        value: [
                            details.text1Length,
                            details.uniqueText1Count,
                            details.commonTermsCount,
                            currentResult.chartData.similarityGauge.score,
                            details.uniqueText1Count / details.text1Length
                        ],
                        name: '文本1',
                        areaStyle: {
                            opacity: 0.3
                        }
                    },
                    {
                        value: [
                            details.text2Length,
                            details.uniqueText2Count,
                            details.commonTermsCount,
                            currentResult.chartData.similarityGauge.score,
                            details.uniqueText2Count / details.text2Length
                        ],
                        name: '文本2',
                        areaStyle: {
                            opacity: 0.3
                        }
                    }
                ]
            }]
        };
    };

// 热力图配置
    const getHeatmapOption = () => {
        if (!currentResult || !currentResult.chartData || !currentResult.chartData.wordFrequency) {
            return {
                title: { text: '暂无数据' }
            };
        }

        const { labels, text1Frequencies, text2Frequencies } = currentResult.chartData.wordFrequency;
        const data = labels.map((label:string, index:number) => [
            index,
            0,
            text1Frequencies[index]
        ]).concat(labels.map((label:string, index:number) => [
            index,
            1,
            text2Frequencies[index]
        ]));

        return {
            title: {
                text: '词频热力分布'
            },
            tooltip: {
                position: 'top',
                formatter: function(params: any) {
                    const value = params.data[2];
                    const textIndex = params.data[1] === 0 ? '文本1' : '文本2';
                    const word = labels[params.data[0]];
                    return `${textIndex}<br />${word}: ${value}`;
                }
            },
            grid: {
                height: '50%',
                top: '10%'
            },
            xAxis: {
                type: 'category',
                data: labels,
                splitArea: {
                    show: true
                }
            },
            yAxis: {
                type: 'category',
                data: ['文本1', '文本2'],
                splitArea: {
                    show: true
                }
            },
            visualMap: {
                min: 0,
                max: Math.max(...text1Frequencies, ...text2Frequencies),
                calculable: true,
                orient: 'horizontal',
                left: 'center',
                bottom: '15%'
            },
            series: [{
                name: '词频分布',
                type: 'heatmap',
                data: data,
                label: {
                    show: true
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
    };

// 饼图配置
    const getPieOptions = () => {
        if (!currentResult || !currentResult.analysisDetails) {
            return [{
                title: { text: '暂无数据' }
            }, {
                title: { text: '暂无数据' }
            }];
        }

        const details = currentResult.analysisDetails;
        const text1Data = [
            { value: details.commonTermsCount || 0, name: '共同词汇' },
            { value: details.uniqueText1Count || 0, name: '独有词汇' }
        ];

        const text2Data = [
            { value: details.commonTermsCount || 0, name: '共同词汇' },
            { value: details.uniqueText2Count || 0, name: '独有词汇' }
        ];
        const pieOption = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 10
            },
            series: [
                {
                    name: '词汇组成',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c} ({d}%)'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    },
                    data: []
                }
            ]
        };

        return [
            {
                ...pieOption,
                title: { text: '文本1词汇组成', left: 'center' },
                series: [{ ...pieOption.series[0], data: text1Data }]
            },
            {
                ...pieOption,
                title: { text: '文本2词汇组成', left: 'center' },
                series: [{ ...pieOption.series[0], data: text2Data }]
            }
        ];
    };

    return (
        <div className={styles.container}>
            <Card title="分析历史记录" className={styles.historyCard}>
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="resultId"
                    pagination={pagination}
                    onChange={handleTableChange}
                    loading={loading}
                    scroll={{ x: 1200 }}
                />
            </Card>

            <Modal
                title="分析结果详情"
                open={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
                width={1200}
                footer={null}
                destroyOnClose
            >
                {detailLoading ? (
                    <div className={styles.loading}>加载中...</div>
                ) : (
                    currentResult && (
                        <div className={styles.resultSection}>
                            <Tabs defaultActiveKey="1">
                                <TabPane tab="相似度概览" key="1">
                                    <Row gutter={[16, 16]}>
                                        <Col span={12}>
                                            <Card title="相似度得分">
                                                <ReactECharts
                                                    option={getEnhancedGaugeOption()}
                                                    style={{ height: '400px' }}
                                                />
                                            </Card>
                                        </Col>
                                        <Col span={12}>
                                            <Card title="文本特征雷达图">
                                                <ReactECharts
                                                    option={getRadarOption()}
                                                    style={{ height: '400px' }}
                                                />
                                            </Card>
                                        </Col>
                                    </Row>

                                </TabPane>

                                <TabPane tab="词频分析" key="2">
                                    <Row gutter={[16, 16]}>
                                        <Col span={24}>
                                            <Card title="词频热力分布">
                                                <ReactECharts
                                                    option={getHeatmapOption()}
                                                    style={{ height: '400px' }}
                                                />
                                            </Card>
                                        </Col>
                                    </Row>
                                    <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                                        <Col span={12}>
                                            <Card title="文本1词汇组成">
                                                <ReactECharts
                                                    option={getPieOptions()[0]}
                                                    style={{ height: '300px', width: '100%' }}
                                                />
                                            </Card>
                                        </Col>
                                        <Col span={12}>
                                            <Card title="文本2词汇组成">
                                                <ReactECharts
                                                    option={getPieOptions()[1]}
                                                    style={{ height: '300px', width: '100%' }}
                                                />
                                            </Card>
                                        </Col>
                                    </Row>
                                </TabPane>

                                <TabPane tab="详细分析" key="3">
                                    <Card title="分析详情" className={styles.detailCard}>
                                        <Row gutter={[16, 16]}>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>文本1长度：</span>
                                                    <span>{currentResult.analysisDetails.text1Length}</span>
                                                </div>
                                            </Col>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>文本2长度：</span>
                                                    <span>{currentResult.analysisDetails.text2Length}</span>
                                                </div>
                                            </Col>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>共同词汇数：</span>
                                                    <span>{currentResult.analysisDetails.commonTermsCount}</span>
                                                </div>
                                            </Col>
                                        </Row>

                                        <div className={styles.segments}>
                                            <h4>相似片段:</h4>
                                            <p>{currentResult.similarSegments || '无'}</p>

                                            <h4>差异片段:</h4>
                                            <p>{currentResult.differentSegments || '无'}</p>
                                        </div>
                                    </Card>
                                </TabPane>
                            </Tabs>
                        </div>
                    )
                )}
            </Modal>
        </div>
    );
};

export default SimilarityAnalysisHistory;
